﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public abstract class TriggerBase : MonoBehaviour
{
    [SerializeField] public VoidEvent m_voidEvent;
    public float delay = 0;
    public bool trigger = false;
    public int triggerMaxCount = int.MaxValue;
    public int triggerCount = 0;
    public EContitionType conditionType;
    public List<BaseCondition> conditionList;

    void Start()
    {
        InitTrigger();
    }

    public virtual void InitTrigger() { }
    public virtual void UpdateTrigger() { }


    // Update is called once per frame
    void Update()
    {
        UpdateTrigger();
    }


    /// <summary>
	/// 触发器触发后，执行的操作
	/// </summary>
	public void OnTrigger()
    {
        if (!VerifyCondition())
        {
            return;
        }
        if (triggerCount < triggerMaxCount)
        {
            if (delay > 0)
                StartCoroutine(TriggerEvent());
            else
                TriggerEventFinal();
        }
        else
        {
            return;
        }
        trigger = true;
        triggerCount++;
    }

    private IEnumerator TriggerEvent()
    {
        yield return new WaitForSeconds(delay);
        TriggerEventFinal();
    }

    /// <summary>
    /// 在基类处理事件，所有参数为属性面板设置的参数
    /// 子类不在处理
    /// </summary>
    private void TriggerEventFinal()
    {
        if (null != m_voidEvent)
        {
            m_voidEvent.Invoke();
        }

    }

    /// <summary>
    /// 重置触发器
    /// </summary>
    public virtual void ResetTrigger()
    {
        trigger = false;
        triggerCount = 0;
    }

    private bool VerifyCondition()
    {
        bool condition = true;
        if (null == conditionList || conditionList.Count < 1)
            return condition;
        if (conditionType == EContitionType.AND)
        {
            condition = true;
            for (int i = 0; i < conditionList.Count; i++)
            {
                if (!conditionList[i].VerifyCondition())
                {
                    condition = false;
                }
            }
        }
        else if (conditionType == EContitionType.OR)
        {
            condition = false;
            for (int i = 0; i < conditionList.Count; i++)
            {
                if (conditionList[i].VerifyCondition())
                {
                    condition = true;
                }
            }
        }
        else if (conditionType == EContitionType.NOT)
        {
            condition = true;
            for (int i = 0; i < conditionList.Count; i++)
            {
                if (conditionList[i].VerifyCondition())
                {
                    condition = false;
                }
            }
        }
        return condition;
    }
    public void ClearAllEvent()
    {
        if (null != m_voidEvent)
        {
            m_voidEvent.RemoveAllListeners();
            m_voidEvent = null;
        }
    }

}
